<template>
  <div class="bg-white/95 backdrop-blur-md rounded-2xl shadow-lg border border-gray-100/50 p-6 overflow-hidden relative">

    <!-- 头部区域 -->
    <div class="flex flex-col lg:flex-row lg:items-center justify-between mb-6 gap-4">
      <!-- 标题区域 -->
      <div class="flex items-center space-x-3">
        <div class="w-10 h-10 rounded-xl bg-gradient-to-br from-[#a2d5c6] to-[#87CEEB] flex items-center justify-center shadow-lg">
          <i class="fas fa-users text-white text-lg"></i>
        </div>
        <div>
          <h3 class="text-2xl font-bold bg-gradient-to-r from-[#a2d5c6] to-[#976df7] bg-clip-text text-transparent">
            社区总览
          </h3>
          <p class="text-sm text-gray-500 mt-0.5">发现你感兴趣的校园社区</p>
        </div>
      </div>

      <!-- 搜索和筛选区域 -->
      <div class="flex flex-col sm:flex-row gap-3 lg:flex-1 lg:max-w-2xl lg:ml-6">
        <!-- 类型筛选按钮 -->
        <div class="flex flex-wrap gap-2">
          <button
            v-for="type in typeList"
            :key="type.value"
            class="px-4 py-2 rounded-xl text-sm font-medium transition-all duration-300 transform hover:scale-105 active:scale-95"
            :class="currentType === type.name
              ? 'bg-gradient-to-r from-[#a2d5c6] to-[#87CEEB] text-white shadow-md'
              : 'bg-gray-50 text-gray-600 hover:bg-gray-100 hover:text-[#a2d5c6] border border-gray-200'"
            @click="findByType(type)"
          >
            {{ type.name }}
          </button>
        </div>

        <!-- 搜索框 -->
        <div class="relative flex-1 min-w-[280px]">
          <div class="relative flex items-center bg-gray-50/80 rounded-xl border border-gray-200/50 hover:border-[#a2d5c6]/50 focus-within:border-[#a2d5c6] focus-within:bg-white transition-all duration-300 shadow-sm hover:shadow-md">
            <div class="absolute left-4 flex items-center justify-center w-4 h-4">
              <i class="fas fa-search text-[#a2d5c6] text-sm"></i>
            </div>
            <input
              type="text"
              v-model="searchQuery"
              placeholder="搜索学校名、社区名、标签..."
              class="w-full pl-12 pr-16 py-3 bg-transparent rounded-xl text-sm text-gray-700 placeholder-gray-400 focus:outline-none"
              @input="handleSearchInput"
            />
            <button
              v-if="searchQuery"
              @click="clearSearch"
              class="absolute right-12 flex items-center justify-center w-6 h-6 rounded-full hover:bg-gray-200/80 transition-all duration-200"
            >
              <i class="fas fa-times text-gray-400 text-xs"></i>
            </button>
            <button
              @click="applyFilters"
              class="absolute right-2 flex items-center justify-center w-8 h-8 bg-gradient-to-r from-[#a2d5c6] to-[#87CEEB] text-white rounded-lg hover:from-[#87CEEB] hover:to-[#976df7] transition-all duration-300 shadow-sm hover:shadow-md transform hover:scale-105 active:scale-95"
            >
              <i class="fas fa-search text-xs"></i>
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 社区卡片网格 -->
    <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
      <!-- 社区卡片 -->
      <div
        v-for="community in paginatedCommunities"
        :key="community.id"
        class="community-card bg-white rounded-2xl overflow-hidden border border-gray-100/50 hover:border-[#a2d5c6]/30 transition-all duration-500 hover:shadow-xl hover:-translate-y-2 group cursor-pointer"
        @click="handleCommunityClick(community.id)"
      >
        <!-- 封面图片区域 -->
        <div class="relative overflow-hidden">
          <img
            :src="community.coverImage || 'https://picsum.photos/400/180?random=' + community.id"
            alt="社区封面"
            class="w-full h-28 object-cover group-hover:scale-110 transition-transform duration-700"
          >
          <!-- 渐变遮罩 -->
          <div class="absolute inset-0 bg-gradient-to-t from-black/70 via-black/20 to-transparent"></div>
          
          <!-- 热度标签 -->
          <div class="absolute top-2 right-2">
            <div class="px-2.5 py-1 rounded-full text-xs font-medium backdrop-blur-md border border-white/30"
                 :class="getHeatLevelClass(community.heatLevel)">
              <i class="fas fa-fire mr-1"></i>
              {{ getHeatLevelText(community.heatLevel) }}
            </div>
          </div>

          <!-- 底部信息 -->
          <div class="absolute bottom-3 left-3 right-3">
            <div class="flex items-center justify-between text-white/90 text-xs">
              <div class="flex items-center space-x-3">
                <span class="flex items-center">
                  <i class="fas fa-users mr-1 text-xs"></i>
                  {{ formatNumber(community.members) }}
                </span>
                <span class="flex items-center">
                  <i class="fas fa-building mr-1 text-xs"></i>
                  {{ community.school }}
                </span>
              </div>
            </div>
          </div>
        </div>

        <!-- 卡片内容区域 -->
        <div class="p-5">
          <!-- 头像和基本信息 -->
          <div class="flex items-start space-x-4 mb-4">
            <div class="relative">
              <div class="w-10 h-10 rounded-xl overflow-hidden border-3 border-white shadow-lg -mt-6 bg-white group-hover:scale-110 transition-transform duration-300">
                <img :src="community.avatar" :alt="community.name" class="w-full h-full object-cover">
              </div>
              <!-- 认证徽章 -->
              <div class="absolute -bottom-1 -right-1 w-4 h-4 bg-gradient-to-r from-[#a2d5c6] to-[#87CEEB] rounded-full flex items-center justify-center">
                <i class="fas fa-check text-white text-xs"></i>
              </div>
            </div>
            <div class="flex items-center space-x-2 mb-1">
              <span class="text text-gray-700">{{ community.name }}</span>
            </div>
            <div class="flex-1 pt-1">

            </div>
          </div>

          <!-- 描述 -->
          <p class="text-sm text-gray-600 line-clamp-2 mb-4 leading-relaxed">
            {{ community.description }}
          </p>

          <!-- 标签 -->
          <div class="flex flex-wrap gap-2 mb-4">
            <span
              v-for="(tag, index) in (community.tags || []).slice(0, 3)"
              :key="tag"
              class="px-2.5 py-1 rounded-lg text-xs font-medium transition-colors duration-200"
              :class="getTagClass(index)"
            >
              {{ tag }}
            </span>
            <span
              v-if="(community.tags || []).length > 3"
              class="px-2.5 py-1 rounded-lg text-xs font-medium bg-gray-100 text-gray-500"
            >
              +{{ (community.tags || []).length - 3 }}
            </span>
          </div>

        </div>
      </div>

      <!-- 骨架屏 -->
      <div v-if="isLoading"
           class="community-card border border-gray-100 rounded-xl overflow-hidden bg-gray-50 animate-pulse">
        <!-- 骨架屏内容保持不变 -->
        <div class="h-40 bg-gray-200"></div>
        <div class="p-4">
          <div class="h-5 w-2/3 bg-gray-200 rounded mb-3"></div>
          <div class="flex space-x-2 mb-4">
            <div class="h-8 w-16 bg-gray-200 rounded"></div>
            <div class="h-8 w-16 bg-gray-200 rounded"></div>
            <div class="h-8 w-16 bg-gray-200 rounded"></div>
          </div>
          <div class="flex items-center space-x-3 mb-4">
            <div class="w-12 h-12 rounded-full bg-gray-200"></div>
            <div class="flex-grow">
              <div class="h-4 w-3/4 bg-gray-200 rounded mb-2"></div>
              <div class="h-4 w-1/2 bg-gray-200 rounded"></div>
            </div>
          </div>
          <div class="space-y-2 mb-4">
            <div class="h-4 w-full bg-gray-200 rounded"></div>
            <div class="h-4 w-full bg-gray-200 rounded"></div>
          </div>
          <div class="mt-4">
            <div class="flex justify-between items-center mb-1">
              <div class="h-3 w-24 bg-gray-200 rounded"></div>
              <div class="h-3 w-12 bg-gray-200 rounded"></div>
            </div>
            <div class="h-1.5 w-full bg-gray-200 rounded-full"></div>
          </div>
          <div class="mt-4 flex justify-between items-center">
            <div class="h-3 w-32 bg-gray-200 rounded"></div>
            <div class="h-3 w-24 bg-gray-200 rounded"></div>
          </div>
        </div>
      </div>
    </div>

    <div class="mt-4">
      <!-- 简化的分页控制 -->
      <div class="flex items-center justify-center gap-4">
        <button
            class="w-9 h-9 flex items-center justify-center rounded-full border border-gray-200 text-gray-500 hover:text-[#79c2a5] hover:border-[#91f0d0] transition-all"
            :class="{ 'opacity-50 cursor-not-allowed': currentPage === 1 }"
            :disabled="currentPage === 1"
            @click="changePage(currentPage - 1)"
        >
          <i class="fa fa-chevron-left"></i>
        </button>
        
        <div class="text-sm text-gray-500">第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</div>
        
        <button
            class="w-9 h-9 flex items-center justify-center rounded-full border border-gray-200 text-gray-500 hover:text-[#79c2a5] hover:border-[#91f0d0] transition-all"
            :class="{ 'opacity-50 cursor-not-allowed': currentPage === totalPages }"
            :disabled="currentPage === totalPages"
            @click="changePage(currentPage + 1)"
        >
          <i class="fa fa-chevron-right"></i>
        </button>
      </div>
    </div>

    <!-- 空状态提示 -->
    <div v-if="!isLoading && filteredCommunities.length === 0"
         class="py-12 flex flex-col items-center justify-center text-center">
      <div class="w-20 h-20 mb-4 rounded-full bg-gray-100 flex items-center justify-center">
        <i class="fa fa-search text-gray-400 text-2xl"></i>
      </div>
      <h4 class="text-lg font-medium text-gray-800 mb-2">没有找到匹配的社区</h4>
      <p class="text-gray-500 max-w-md">尝试使用不同的关键词或标签筛选，或者查看所有社区</p>
      <button class="mt-4 px-4 py-2 bg-[#79c2a5] text-white rounded-lg hover:bg-[#5cd3a3] transition-colors"
              @click="resetFilters">
        查看所有社区
      </button>
    </div>
  </div>
</template>

<script>
import {communityOverviewData} from "@/mock/communityOverviewData";

export default {
  name: "CommunityOverview",
  data() {
    return {
      communityOverviews: communityOverviewData,
      currentPage: 1,
      itemsPerPage: 6, // 每页显示6个社区
      typeList: [
        {
          name: '全部',
          value: 1
        },
        {
          name: '校内',
          value: 2
        },
        {
          name: '参与',
          value: 3
        },
      ],
      currentType: '全部',
      isLoading: false,
      searchQuery: '',      // 搜索框内容
      selectedSchool: '',   // 选中的学校
      debounceTimer: null   // 防抖计时器
    };
  },
  computed: {
    // 获取所有不同的学校
    availableSchools() {
      const schools = new Set();
      this.communityOverviews.forEach(community => {
        if (community.school) {
          schools.add(community.school);
        }
      });
      return Array.from(schools);
    },

    // 获取所有不同的标签
    uniqueTags() {
      const tags = new Set();
      this.communityOverviews.forEach(community => {
        if (community.tags) {
          community.tags.forEach(tag => tags.add(tag));
        }
      });
      return Array.from(tags);
    },

    // 过滤后的社区 - 结合所有筛选条件
    filteredCommunities() {
      let filtered = this.communityOverviews;

      // 按学校筛选
      if (this.selectedSchool) {
        filtered = filtered.filter(community =>
            community.school === this.selectedSchool
        );
      }

      // 按搜索关键词筛选
      if (this.searchQuery.trim()) {
        const query = this.searchQuery.toLowerCase().trim();
        filtered = filtered.filter(community =>
            community.name.toLowerCase().includes(query) ||
            (community.description && community.description.toLowerCase().includes(query)) ||
            (community.tags && community.tags.some(tag => tag.toLowerCase().includes(query)))
        );
      }

      // 按类型筛选
      if (this.currentType && this.currentType !== '全部') {
        if (this.currentType === '我的学校') {
          // 这里假设当前用户学校是"示例大学"，实际应用中应从用户会话获取
          const userSchool = "示例大学";
          filtered = filtered.filter(community => community.school === userSchool);
        } else if (this.currentType === '与我相关') {
          // 这里只是示例，实际应用中应根据用户关注的社区等逻辑筛选
          filtered = filtered.filter((_, index) => index % 3 === 0);
        } else {
          filtered = filtered.filter(community =>
              community.tags && community.tags.includes(this.currentType)
          );
        }
      }

      return filtered;
    },

    // 当前页应该显示的社区信息
    paginatedCommunities() {
      const start = (this.currentPage - 1) * this.itemsPerPage;
      const end = start + this.itemsPerPage;
      return this.filteredCommunities.slice(start, end);
    },

    // 计算总页数
    totalPages() {
      return Math.ceil(this.filteredCommunities.length / this.itemsPerPage);
    }
  },
  methods: {
    // 切换页码
    changePage(page) {
      if (page >= 1 && page <= this.totalPages) {
        this.currentPage = page;
        // 滚动到顶部
        this.$el.scrollIntoView({ behavior: 'smooth', block: 'start' });
      }
    },

    // 处理社区卡片点击事件
    handleCommunityClick(communityId) {
      // 使用Vue Router导航到communityHome页面，并传递社区ID作为参数
      this.$router.push({
        name: 'communityHome',
        query: { id: communityId }
      });
    },

    // 按标签筛选
    findByType(type) {
      this.currentType = type.name;
      this.currentPage = 1; // 重置页码
      this.showLoading();
    },

    // 搜索输入处理（防抖）
    handleSearchInput() {
      if (this.debounceTimer) {
        clearTimeout(this.debounceTimer);
      }
      this.debounceTimer = setTimeout(() => {
        this.applyFilters();
      }, 500);
    },

    // 清除搜索
    clearSearch() {
      this.searchQuery = '';
      this.applyFilters();
    },

    // 应用筛选条件
    applyFilters() {
      this.currentPage = 1; // 重置页码
      this.showLoading();
    },

    // 重置筛选
    resetFilters() {
      this.currentType = '全部社团';
      this.searchQuery = '';
      this.selectedSchool = '';
      this.currentPage = 1;
      this.showLoading();
    },

    // 显示加载状态
    showLoading() {
      this.isLoading = true;
      setTimeout(() => {
        this.isLoading = false;
      }, 800);
    },

    // 格式化日期
    formatDate(dateString) {
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric', 
        month: 'short', 
        day: 'numeric'
      });
    },

    // 格式化数字
    formatNumber(num) {
      if (num >= 10000) {
        return (num / 10000).toFixed(1) + 'w';
      } else if (num >= 1000) {
        return (num / 1000).toFixed(1) + 'k';
      }
      return num.toString();
    },

    // 获取热度等级样式
    getHeatLevelClass(level) {
      if (level >= 80) {
        return 'bg-red-500/90 text-white';
      } else if (level >= 60) {
        return 'bg-orange-500/90 text-white';
      } else if (level >= 40) {
        return 'bg-yellow-500/90 text-white';
      } else {
        return 'bg-blue-500/90 text-white';
      }
    },

    // 获取热度等级文本
    getHeatLevelText(level) {
      if (level >= 80) {
        return '火爆';
      } else if (level >= 60) {
        return '热门';
      } else if (level >= 40) {
        return '活跃';
      } else {
        return '普通';
      }
    },

    // 获取标签样式
    getTagClass(index) {
      const classes = [
        'bg-[#a2d5c6]/10 text-[#a2d5c6] border border-[#a2d5c6]/20',
        'bg-[#87CEEB]/10 text-[#87CEEB] border border-[#87CEEB]/20',
        'bg-[#976df7]/10 text-[#976df7] border border-[#976df7]/20'
      ];
      return classes[index % classes.length];
    }
  },
  created() {
    this.showLoading();
  }
};
</script>

<style scoped>
/* 毛玻璃效果 */
@supports ((-webkit-backdrop-filter: blur(20px)) or (backdrop-filter: blur(20px))) {
  .backdrop-blur-md {
    backdrop-filter: blur(20px);
    -webkit-backdrop-filter: blur(20px);
  }
}

/* 社区卡片样式 */
.community-card {
  transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1);
  transform-origin: center;
}

.community-card:hover {
  box-shadow: 
    0 20px 40px -12px rgba(162, 213, 198, 0.25),
    0 8px 16px -4px rgba(162, 213, 198, 0.1),
    0 0 0 1px rgba(162, 213, 198, 0.05);
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 渐变文字效果 */
.bg-clip-text {
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
}

/* 活跃度进度条动画 */
@keyframes progressFill {
  from {
    width: 0%;
  }
  to {
    width: var(--progress-width);
  }
}

.community-card:hover .h-2 > div {
  animation: progressFill 1s ease-out;
}

/* 图片悬停效果 */
.community-card img {
  transition: transform 0.7s cubic-bezier(0.4, 0, 0.2, 1);
}

/* 标签悬停效果 */
.community-card .px-2\.5:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

/* 按钮悬停效果 */
.community-card button:hover {
  transform: translateY(-1px) scale(1.05);
}

/* 头像悬停效果 */
.community-card .w-12:hover {
  transform: scale(1.1) rotate(5deg);
}

/* 加载动画 */
@keyframes shimmer {
  0% {
    background-position: -200px 0;
  }
  100% {
    background-position: calc(200px + 100%) 0;
  }
}

.animate-pulse {
  animation: shimmer 2s infinite linear;
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200px 100%;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .community-card {
    margin-bottom: 1rem;
  }
  
  .community-card .h-28 {
    height: 120px;
  }
}

/* 搜索框聚焦效果 */
.focus-within\:border-\[\#a2d5c6\]:focus-within {
  border-color: #a2d5c6;
  box-shadow: 0 0 0 3px rgba(162, 213, 198, 0.1);
}
</style>
